<!-- 每一项编辑文本的组件 -->
<template>
  <NodeViewWrapper class="vue-component">
    <div contenteditable="false" class="editor_content_ele_point" @click="listen"
      @mouseenter.stop="state.isHover = true" @mouseleave.stop="state.isHover = false">
      <!-- 此项有音频, 并且仓库中的音频和此项的音频相同 -->
      <template v-if="
        !!editItem?.audio_url &&
        VideoPlayingData?.audio_url ==
        editItem?.audio_url
      ">
        <!-- 播放或暂停状态 -->
        <PauseOutlined v-if="VideoPlayingData.isPlay" style="color: #0c0d0e" />
        <CaretRightOutlined v-else style="color: #0c0d0e" />
      </template>
      <!-- 此项没有音频 或者 正在播放的音频与此项不同 -->
      <template v-else>
        <!-- 点击了此项, 进入了加载状态 -->
        <template v-if="listenLoding">
          <LoadingOutlined> </LoadingOutlined>
        </template>
        <template v-else>
          <span data-slate-zero-width="true" contenteditable="false">
            <cu-icon type="icon-dian" v-show="!state.isHover" contenteditable="false"></cu-icon>
            <cu-icon type="icon-yinliang01" style="color: #1664ff" v-show="state.isHover"
              contenteditable="false"></cu-icon>
          </span>
        </template>
        <!-- hover -->
        <!-- 充值弹窗 -->
        <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>

      </template>
    </div>
    <NodeViewContent class="content" />

  </NodeViewWrapper>
</template>

<script setup>
// 全局轻提示
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import { nanoid } from "nanoid";
// 对小圆点去重获取音色
import { getRandomItemVoice } from '@/common/utils/richTextProcessing.js'
import { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'
import { computed, ref, onMounted, watch, reactive } from 'vue'
import {
  LoadingOutlined,
  PauseOutlined,
  CaretRightOutlined
} from "@ant-design/icons-vue";

// import { ssmlGetVoice } from '@/common/utils/richTextProcessing.js'

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)


// 仓库中的全部音色数据
const allVoiceData = computed(() => {
  return store.state.videoMixCut.allVoiceData;
});

import { useStore } from "vuex";

import { getSsmlcontent, getAudioData_Set } from '@/views/shotstack/MixedCutPlatforms/utools/index.js'
const store = useStore();

// 仓库中的字幕数据
const subTitle = computed(() => {
  return store.state.videoMixCut.Global_tts_config;
});

const props = defineProps({
  node: Object,
  editor: Object
})

const state = reactive({
  isHover: false
})

// 本项subtitle的id
const subId = computed(() => {
  // 如果遇到中间回车, 导致subId重复, 修改此项的subId
  const tts_index = subTitle.value.configs.findIndex(ele => ele.tts_id == tts_id.value)
  const isFindIndex = subTitle.value.configs[tts_index].subtitle.findIndex(ele => ele.subtitle_id == props.node.attrs.subId)
  if (isFindIndex != -1) {
    const id = nanoid()
    const filterArr = subTitle.value.configs[tts_index].subtitle.filter(ele => ele.subtitle_id == props.node.attrs.subId)
    if (filterArr.length > 1) {
      props.updateAttributes({ subId: id })
    }
  }
  return props.node.attrs.subId
})

// 抽屉中编辑的字幕组的id
const tts_id = computed(() => {
  return store.state.videoMixCut.global_edit_tts_id
})

// // 找到的本项数据
const editItem = computed(() => {
  const tts_index = subTitle.value.configs.findIndex(ele => ele.tts_id == tts_id.value)
  if (tts_index == -1) return null
  return subTitle.value.configs[tts_index].subtitle.find(ele => ele.subtitle_id == subId.value)
  // return subTitle.value.configs[0].subtitle.find(ele => ele.subtitle_id == props.node.attrs.subId)
})

// 当前编辑的tts项
const target_tts = computed(() => {
  return subTitle.value.configs.find(ele => ele.tts_id == tts_id.value)
})

// 仓库中的音频播放数据
const VideoPlayingData = computed(() => {
  return store.state.videoMixCut.VideoPlayingData
})

const isPlay = ref(false) // true => 播放中  false => 暂停中
const listenLoding = ref(false) // true => 加载中  false => 加载完成

// 点击项
const listen = async () => {
  // 获得此项的 用于试听的ssml结构
  const ssmlData = getSsmlcontent(props.node.content.content)
  // debugger
  // return
  if (ssmlData.isEmpty || ssmlData.text == '') return message.warning("当前预览单句中存在空行或不可配音的单行文本，请确认后保存设置!");
  if (listenLoding.value) return

  // 当前项的url没有清空 => 并且正在播放 => 暂停 else => 播放
  // 如果当前有音频链接
  if (editItem.value.audio_url != '') {
    // 当前播放的和本项的音频相同
    if (VideoPlayingData.value.audio_url == editItem.value.audio_url) {
      // 判断音频的播放状态
      if (VideoPlayingData.value.isPlay) {
        // 暂停
        store.commit("videoMixCut/SETVIDEOPLAYING_DATA", {
          isPlay: false,
          audio_url: editItem.value.audio_url,
          reset: false, // 是否从头播放
          changeUrl: false, // 是否修改url
        })
        // isPlay.value = false
      } else {
        // 播放
        store.commit("videoMixCut/SETVIDEOPLAYING_DATA", {
          isPlay: true,
          audio_url: editItem.value.audio_url,
          reset: false, // 是否从头播放
          changeUrl: false, // 是否修改url
        })
        // isPlay.value = true
      }
    } else {
      // 直接播放
      store.commit("videoMixCut/SETVIDEOPLAYING_DATA", {
        isPlay: true,
        audio_url: editItem.value.audio_url,
        reset: true, // 是否从头播放
        changeUrl: true, // 是否修改url
      })
      // isPlay.value = true
    }
  } else {

    // 没有url => 重新获取播放链接
    const text_subTitle = subTitle.value.configs.filter(ele => {
      // 筛选出除了自身以外的 tts项
      // && ele.tts_id != target_tts.value.tts_id
      if (subTitle.value.configs_type == "text" && ele.tts_id != target_tts.value.tts_id) {
        return ele.tab_id == 'text'
      } else {
        return ele.tab_id == 'audio'
      }
    })

    try {
      const res = await utils.textConfigGet({
        number: ssmlData.text.length
      })
      // 查询积分, 积分不足则走不到这一步

      // 获取积分消耗提示内容
      // const content = utils.useText(res)
      // try {
      //   // 确认消耗
      //   await utils.kd({ content,res })
      // } catch (error) {
      //   return
      // }
    } catch (error) {
      vipVisible.value = true
      vipModalRef.value && vipModalRef.value.openBuyVisible()
      return

    }

    // 获取当前所有 tts项使用的 音色
    let voiceArr = [];
    text_subTitle.forEach((ele) => {
      const findIndex = allVoiceData.value.findIndex(
        (i) => i.timbre_id == ele.tone_id
      );
      findIndex != -1 && voiceArr.push(allVoiceData.value[findIndex].timbre_id);
    });

    // 判断是否已经有了音频, 有了音频则不改变原本的音色
    const haveVoice = target_tts.value.subtitle.some(i => i.audio_url
    )
    let voiceItem
    // 如果此项和其他tts使用的音频相同, 并且 则更换一个试听的音色, 并且修改此项的音色
    // debugger
    if (voiceArr.includes(target_tts.value.tone_id) && !haveVoice) {

      if (subTitle.value.isRandom) {
        voiceItem = await getRandomItemVoice({
          tts_arr: text_subTitle, allVoiceData: allVoiceData.value
        })
        console.log(voiceItem, '获取的随机音色');
        // debugger
        target_tts.value.tone_id = voiceItem.timbre_id
        target_tts.value.category = voiceItem.category
        target_tts.value.voice_type = voiceItem.voice_type
        target_tts.value.id = voiceItem.id
      } else {
        // 从勾选的音色中选择一个
        const index = Math.floor(Math.random() * target_tts.value.selectVoice.length)
        const item = target_tts.value.selectVoice[index]
        target_tts.value.tone_id = item.tone_id
        target_tts.value.category = item.category
        target_tts.value.voice_type = item.voice_type
        target_tts.value.id = item.id
      }
    } else if (!subTitle.value.isRandom && !haveVoice) {
      // 从勾选的音色中选择一个
      const index = Math.floor(Math.random() * target_tts.value.selectVoice.length)
      const item = target_tts.value.selectVoice[index]
      target_tts.value.tone_id = item.tone_id
      target_tts.value.category = item.category
      target_tts.value.voice_type = item.voice_type
      target_tts.value.id = item.id
    }
    // return
    getAudioData_Set({
      ssmlData, editItem, target_tts, listenLoding, subTitle, isPlay, mexid_all: false
    })
  }
};



</script>

<style lang="less" scoped>
.vue-component {
  color: #000;
  position: relative;
  padding: 5px 20px;

  .content {
    margin: 5px 0;
  }

  .editor_content_ele_point {
    cursor: pointer;
    color: #c7ccd6;
    position: absolute;
    left: 2px;
    top: 20px;
    transform: translateY(-50%);
  }

}
</style>